<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>聊天室</title>
    <link rel="stylesheet" type="text/css" href="css/index.css"/>
</head>
<body>
    <div class="main">
        <div class="main-top">
            <h3>聊天测试</h3>
            <div class="info ellipsis">当前共有<span class="chatNum">0</span>人在线。在线列表:<span class="chatList"></span>
            </div>
        </div>
        <div class="main-body">
            <!-- <section class="chatRoomTip">
                <div>加入到聊天室</div>
            </section>
            <section class="user clearfix">
                <span>用户</span>
                <div>
                    1213asda
                </div>
            </section>
            <section class="server clearfix">
                <span>用户</span>
                <div>
                    多行12312asdba多行多行12312asdba多行多行12312asdba多行多行12312asdba多行多行12312asdba多行
                </div>
            </section> -->
        </div>
        <div class="main-footer clearfix">
            <button type="button" class="send" id="sendmess">发送</button>
            <div class="input">
                <input type="text" name="msg" id="msg" value="" />
            </div>
            <input class = "file-input" type = "file" accept="image/*"/>
            <button type="button" class="send pic">+</button>
        </div>
    </div>
    <script src="js/jquery-2.1.0.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/imageUnitl.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/socket.io.js" type="text/javascript" charset="utf-8"></script>
    <script>
        /*按钮点击效果*/
        $('.send').mousedown(function(){
            $(this).addClass("down");
        })
        $('.send').mouseup(function(){
            $(this).removeClass("down");
        })
        /*socket*/
        window.onload=function () {
            // return false;
              var username=prompt('请输入您的姓名');
              if (!username){
                  alert('姓名必填');
                  history.go(0);
              }
            // username="初始化用户";
            userId=genUid();
            var userInfo={
                'userid':userId,
                'username':username
            };
            //连接socket后端服务器
            var socket=io.connect("ws://127.0.0.1:4000");
            // var socket=io.connect("ws://101.132.243.231:8088");
            //通知用户有用户登录
            socket.emit('login',userInfo);
            //监听新用户登录
            socket.on('login',function (o) {
                updateMsg(o, 'login');
            });
            //监听用户退出
            socket.on('logout',function (o) {
                updateMsg(o, 'logout');
            });
            //接收发送消息
            socket.on('message',function (obj) {
                // 通过用户id判断展示位置和内容标签
                var content = '<div>'+obj.content+'</div>';
                if(obj.img){
                    content = '<div><img class = "mess-img" src="data:image/png;base64,'+obj.img+'"></div>';
                }
                if(obj.userid==userId) {
                    var MsgHtml='<section class="user clearfix">'
                                        +'<span>'+obj.username+'</span>'
                                        +content
                                     +'</section>';
                }else{
                    var MsgHtml='<section class="server clearfix">'
                                         +'<span>'+obj.username+'</span>'
                                         +content
                                      +'</section>';
                }
                // 插入内容 滚动底部
                $('.main-body').append(MsgHtml);
                $('.main-body').scrollTop(99999);
            })
            //发送消息
            $('#sendmess').click(function () {
                var content=$('input[name="msg"]').val();
                if (content){
                    var obj={
                        'userid':userId,
                        'username':username,
                        'content':content
                    }
                    socket.emit('message',obj);
                    $('input[name="msg"]').val("");
                }
            })
            // 图片选择 发送图片
            $(".file-input").change(function(){
                var url = URL.createObjectURL($(".file-input")[0].files[0]);
                imageUnitl.getImageBase64ByPath(url, function(data){
                    var obj={
                        'userid':userId,
                        'username':username,
                        'img':data
                    }
                    socket.emit('message',obj);
                }, null, null, 100)
            })

        }

        /*用户id生成*/
        function  genUid() {
            return new Date().getTime()+""+Math.floor(Math.random()*899+100);
        }
        function logout(){
            socket.disconnect();
            location.reload();
        }
        /*监听函数*/
        function updateMsg(o,action) {
            //当前在线列表
            var onlineUser=o.onlineUser;
            //当前在线数
            var onlineCount=o.onlineCount;
            //新加用户
            var user=o.user;
            //更新在线人数
            var userList='';
            var separator = '';
            for(key in onlineUser){
                userList+=separator+onlineUser[key];
                separator = '、';
            }
            //跟新房间信息
            $('.chatNum').text(onlineCount);
            $('.chatList').text(userList);
            $('.info').attr("title", userList)
            //系统消息
            if(action=='login'){
                var sysHtml='<section class="chatRoomTip"><div>'+user.username+'来了</div></section>';
            }
            if(action=="logout"){
                var sysHtml='<section class="chatRoomTip"><div>'+user.username+'已经退出</div></section>';
            }
            // 插入内容 滚动底部
            $(".main-body").append(sysHtml);
            $('.main-body').scrollTop(99999);
        }
    </script>
</body>
</html>